/**
 * @Date: Feb 19, 2010 7:03:29 PM
 */
package com.philip.journal.core.controller;

import java.io.IOException;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.philip.journal.core.Constant;
import com.philip.journal.core.exception.JournalException;

/**
 * @author cry30
 */
public class LoginFilter implements Filter {

    /** Instance logger. */
    private final Logger logger = Logger.getLogger(getClass()); // NOPMD by r39

    @Override
    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
            final FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException {

        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;

        final HttpSession session = request.getSession();
        final String url = request.getRequestURI();

        final boolean loginPage = url.indexOf("login") != -1;
        final boolean libPage = url.indexOf("/lib/extjs") != -1;
        final boolean isResource = url.indexOf("/resource/") != -1;

        if (!(loginPage || libPage || isResource) && session.getAttribute(SessionConstant.USER) == null) {
            final String newurl = request.getContextPath() + "/login";
            response.sendRedirect(newurl);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
        final StringBuilder version = new StringBuilder();
        if (getClass().getPackage().getSpecificationVersion() == null
                || "".equals(getClass().getPackage().getSpecificationVersion())) {
            final ResourceBundle resBundle = ResourceBundle.getBundle("app");
            version.append(resBundle.getString("app.version"));
            final Properties properties = new Properties();
            try {
                properties.load(getClass().getResourceAsStream("/build.num"));
                version.append("-b" + (Integer.parseInt(properties.getProperty("build.number")) - 1));
            } catch (final IOException e) {
                throw new JournalException(e.getMessage(), e);
            }
        }
        logger.info("version: " + version);
        filterConfig.getServletContext().setAttribute(Constant.APP_VERSION, version);
    }

	@Override
	public void destroy() {
		logger.info(this.getClass() + "destroyed.");
	}
}
